package com.codeworker.app.ui.wrapper;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.os.Process;
import android.util.Log;

import java.util.LinkedList;

/**
 * 参考：https://juejin.cn/post/6844903543745282055
 */
public class MyApplication extends Application {

    // 此处采用 LinkedList作为容器，增删速度快
    public static LinkedList<Activity> activityLinkedList;


    @Override
    public void onCreate() {
        super.onCreate();

        activityLinkedList = new LinkedList<>();

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                Log.d("TAG", "onActivityCreated: " + activity.getLocalClassName());
                activityLinkedList.add(activity);
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                Log.d("TAG", "onActivityDestroyed: " + activity.getLocalClassName());
                activityLinkedList.remove(activity);
            }

            @Override
            public void onActivityStarted(Activity activity) {
            }

            @Override
            public void onActivityResumed(Activity activity) {
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }


        });
    }

    public static void exitApp() {
        // 逐个退出Activity
        for (Activity activity : activityLinkedList) {
            activity.finish();
        }

        //  结束进程
        Process.killProcess(Process.myPid());
        System.exit(0);
    }

}